<template>
  <div style="width: 100%;height: 100%">
    <div class="super-flow-demo1">
      <div class="node-container">
        <span
            class="node-item"
            v-for="(item,index) in nodeItemList"
            :key="index"
            @mousedown="evt => nodeItemMouseDown(evt, item.value)">
          {{ item.label }}
        </span>
      </div>
      <div
          class="flow-container"
          ref="flowContainer">
        <super-flow
            ref="superFlow"
            :node-list="nodeList"
            :link-list="linkList"
            :graph-menu="graphMenu"
            :node-menu="nodeMenu"
            :link-base-style="linkBaseStyle"
            :link-style="linkStyle"
            :link-desc="linkDesc">
          <template v-slot:node="{meta}">
            <div
                @mouseup="nodeMouseUp"
                @click="nodeClick(meta)"
                :class="['flow-node','ellipsis',meta.state]">
              {{ meta.name }}
              <i :class="getIcon(meta.state)"></i>
            </div>
          </template>
        </super-flow>
      </div>
    </div>
    <attr-panel :visibleAble.sync="attrPanel.visible" :meta="attrPanel.meta" :id="attrPanel.id"></attr-panel>
    <progress-dialog :visibleAble.sync="showProgress"  :id="uuid"></progress-dialog>
    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="30%"
    >
      <el-input v-model="modelName" placeholder="请输入模型名称"></el-input>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submit">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import ModelList from "@/components/template/ModelManager";
// import Common from "@/lib/Common";
import AttrPanel from "@/components/AttrPanel";
import ProgressDialog from "@/components/ProgressDialog";
import api_story from "@/api/api_story";

const drawerType = {
  node: 0,
  link: 1
}

export default {
  name: 'WorkView',
  components: {AttrPanel,ProgressDialog},
  data() {
    const that = this;
    return {
      modelName: "",//模型名称
      dialogVisible: false,//保存窗口可见
      nodeList: [],
      linkList: [],
      attrPanel: {
        visible: false,
        meta: null,
        id: ""
      },
      drawerType,

      drawerConf: {
        title: '',
        visible: false,
        type: null,
        info: null,
      },
      linkSetting: {
        desc: ''
      },
      nodeSetting: {
        name: '',
        desc: ''
      },

      dragConf: {
        isDown: false,
        isMove: false,
        offsetTop: 0,
        offsetLeft: 0,
        clientX: 0,
        clientY: 0,
        ele: null,
        info: null
      },
      nodeItemList: [],

      graphMenu: [
        [
          {
            // 选项 label
            label: '运行',
            // 选项是否禁用
            disable(graph) {
              return !graph.nodeList.length > 0
            },
            // 选项选中后回调函数
            selected(graph) {
              console.log(graph.toJSON())
              that.startTask()
              // let {linkList, nodeList} = graph.toJSON();
              // let ids = Common.getModelIdByOrder(linkList)
              // console.log(ids)
              // nodeList[0].meta.state = "success"

            }
          },
          {
            label: '保存',
            // 选项是否禁用
            disable(graph) {
              return !graph.nodeList.length > 0
            },
            selected(graph) {
              let allInfo = graph.toJSON()
              localStorage.setItem("linkList", JSON.stringify(allInfo.linkList))
              localStorage.setItem("nodeList", JSON.stringify(allInfo.nodeList))
              that.dialogVisible = true;
            }
          },
        ],
      ],
      nodeMenu: [
        [
          {
            label: '删除',
            selected: node => {
              node.remove()
            }
          },
          {
            label: '编辑',
            selected: node => {
              this.editNode(node)
            }
          }
        ]
      ],
      linkMenu: [
        [
          {
            label: '删除',
            selected: link => {
              link.remove()
            }
          },
          {
            label: '编辑',
            selected: link => {
              this.drawerConf.open(drawerType.link, link)
            }
          }
        ]
      ],

      linkBaseStyle: {
        color: '#666666',           // line 颜色
        hover: '#FF0000',           // line hover 的颜色
        textColor: '#666666',       // line 描述文字颜色
        textHover: '#FF0000',       // line 描述文字 hover 颜色
        font: '14px Arial',         // line 描述文字 字体设置 参考 canvas font
        dotted: false,              // 是否是虚线
        lineDash: [4, 4],           // 虚线时生效
        background: 'rgba(255,255,255,0.6)'    // 描述文字背景色
      },
      fontList: [
        '14px Arial',
        'italic small-caps bold 12px arial'
      ],
      uuid: "",
      showProgress:false,
    }
  },
  created() {


    this.nodeItemList = [];
    for (let i = 0; i < ModelList.length; i++) {
      let item = ModelList[i];
      this.nodeItemList.push({
        label: item.meta.label || "未命名",
        value: () => (JSON.parse(JSON.stringify(item)))
      },)
    }


  },
  mounted() {
    document.addEventListener('mousemove', this.docMousemove)
    document.addEventListener('mouseup', this.docMouseup)
    this.$once('hook:beforeDestroy', () => {
      document.removeEventListener('mousemove', this.docMousemove)
      document.removeEventListener('mouseup', this.docMouseup)
    })
    if (this.$route.query.id) {
      api_story.getDetailById(this.$route.query.id).then(res => {
        console.error(res.data)
        this.uuid=res.data.uuid;
        this.modelName=res.data.name;
        this.linkList=JSON.parse(res.data.linkList);
        this.nodeList=JSON.parse(res.data.nodeList);
      }).catch(err => {
        console.error(err)
      })
    }
  },
  methods: {
    startTask(){
      if(!this.uuid){
        this.$message.error("请先保存");
        return
      }

      const loading = this.$loading({
        lock: true,
        text: '保存中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.showProgress=true;
      api_story.startTask(this.uuid).then(res=>{
        if (res.code === 0) {
          this.$message.success("任务已开始");
        } else {
          this.$message.error("任务创建失败");
        }
      }).catch(err=>{
        console.error(err)
        this.$message.error("任务创建失败");
      }).finally(()=>{
        loading.close()
      })
    },
    /**
     * 保存信息
     * */
    submit() {
      const loading = this.$loading({
        lock: true,
        text: '保存中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      api_story.saveStory({
        name: this.modelName,
        nodeList: localStorage.getItem("nodeList"),
        linkList: localStorage.getItem("linkList"),
        uuid: this.uuid
      }).then(res => {
        if (res.code === 0) {
          this.uuid = res.data
          this.$message.success("保存成功");
          this.dialogVisible = false;
        } else {
          this.$message.error("保存失败");
        }
      }).catch(err => {
        console.error(err)
        this.$message.error(err);
      }).finally(() => {
        loading.close();
      })
    },
    /**
     * 编辑节点
     * */
    editNode(node) {
      this.attrPanel.id = node.id;
      this.attrPanel.meta = node.meta;
      this.attrPanel.visible = true;
    },
    /**
     * 不同状态不同图标
     * @param value
     * @returns {string}
     */
    getIcon(value) {
      let icon = ""
      switch (value) {
        case "success":
          icon = "el-icon-check"
          break;
        case "doing":
          icon = "el-icon-loading"
          break;
        case "fail":
          icon = "el-icon-close"
          break;
      }
      return icon
    },
    linkStyle(link) {
      if (link.meta && link.meta.desc === '1') {
        return {
          color: 'red',
          hover: '#FF00FF',
          dotted: true
        }
      } else {
        return {}
      }
    },
    linkDesc(link) {
      return link.meta ? link.meta.desc : ''
    },
    settingSubmit() {
      const conf = this.drawerConf
      if (this.drawerConf.type === drawerType.node) {
        if (!conf.info.meta) conf.info.meta = {}
        Object.keys(this.nodeSetting).forEach(key => {
          this.$set(conf.info.meta, key, this.nodeSetting[key])
        })
        this.$refs.nodeSetting.resetFields()
      } else {
        if (!conf.info.meta) conf.info.meta = {}
        Object.keys(this.linkSetting).forEach(key => {
          this.$set(conf.info.meta, key, this.linkSetting[key])
        })
        this.$refs.linkSetting.resetFields()
      }
      conf.visible = false
    },
    nodeMouseUp(evt) {
      evt.preventDefault()
    },
    nodeClick(a, b, c) {
      console.log(arguments)
      console.log(a, b, c)
    },
    docMousemove({clientX, clientY}) {
      const conf = this.dragConf

      if (conf.isMove) {

        conf.ele.style.top = clientY - conf.offsetTop + 'px'
        conf.ele.style.left = clientX - conf.offsetLeft + 'px'

      } else if (conf.isDown) {

        // 鼠标移动量大于 5 时 移动状态生效
        conf.isMove =
            Math.abs(clientX - conf.clientX) > 5
            || Math.abs(clientY - conf.clientY) > 5

      }
    },
    docMouseup({clientX, clientY}) {
      const conf = this.dragConf
      conf.isDown = false

      if (conf.isMove) {
        const {
          top,
          right,
          bottom,
          left
        } = this.$refs.flowContainer.getBoundingClientRect()

        // 判断鼠标是否进入 flow container
        if (
            clientX > left
            && clientX < right
            && clientY > top
            && clientY < bottom
        ) {

          // 获取拖动元素左上角相对 super flow 区域原点坐标
          const coordinate = this.$refs.superFlow.getMouseCoordinate(
              clientX - conf.offsetLeft,
              clientY - conf.offsetTop
          )

          // 添加节点
          this.$refs.superFlow.addNode({
            coordinate,
            ...conf.info
          })

        }

        conf.isMove = false
      }

      if (conf.ele) {
        conf.ele.remove()
        conf.ele = null
      }
    },
    nodeItemMouseDown(evt, infoFun) {
      const {
        clientX,
        clientY,
        currentTarget
      } = evt

      const {
        top,
        left
      } = evt.currentTarget.getBoundingClientRect()

      const conf = this.dragConf
      const ele = currentTarget.cloneNode(true)

      Object.assign(this.dragConf, {
        offsetLeft: clientX - left,
        offsetTop: clientY - top,
        clientX: clientX,
        clientY: clientY,
        info: infoFun(),
        ele,
        isDown: true
      })

      ele.style.position = 'fixed'
      ele.style.margin = '0'
      ele.style.top = clientY - conf.offsetTop + 'px'
      ele.style.left = clientX - conf.offsetLeft + 'px'
      this.$el.appendChild(this.dragConf.ele)
    }
  }
}

</script>

<style lang="less">
.ellipsis {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  word-wrap: break-word;
}

.link-base-style-form {
  .el-form-item {
    margin-bottom: 12px;
  }

  padding-bottom: 20px;
  border-bottom: 1px solid #DCDCDC;
}

.super-flow-demo1 {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  @list-width: 200px;


  > .node-container {
    width: @list-width;
    float: left;
    height: 100%;
    text-align: center;
    background-color: #FFFFFF;
  }

  > .flow-container {
    width: calc(100% - @list-width);
    float: left;
    height: 100%;
    overflow: hidden;
  }

  .super-flow__node {
    .flow-node {
      box-sizing: border-box;
      width: 100%;
      height: 100%;
      line-height: 40px;
      font-size: 12px;
      text-align: center;
    }

    border: none;
  }
}

.node-item {
  @node-item-height: 30px;

  font-size: 14px;
  display: inline-block;
  height: @node-item-height;
  width: 120px;
  margin-top: 20px;
  background-color: #FFFFFF;
  line-height: @node-item-height;
  box-shadow: 1px 1px 4px rgba(0, 0, 0, 0.3);
  cursor: pointer;
  user-select: none;
  text-align: center;
  z-index: 6;

  &:hover {
    box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.4);
  }
}

.normal {
  background-color: #F2F6FC;
  color: black;
}

.fail {
  background-color: #F56C6C;
  color: white;
}

.success {
  background-color: #67C23A;
  color: white;
}

.doing {
  background-color: #409EFF;
  color: white;
}
</style>
